#include "../xglog/xglog.h"
#include <vector>
#include <thread>
#include <chrono>
void bench(const std::string &logger_name, size_t thr_count, size_t msg_count, size_t msg_len)
{
  // 1.获取日志器
  xglog::Logger::ptr logger = xglog::getLogger(logger_name);
  if (logger.get() == nullptr)
    return;
  // 2.组织指定长度的日志消息
  std::string msg(msg_len - 1, 'A'); // 少一个字，是为了添加换行
  // 3.创建指定数量的线程
  std::vector<std::thread> threads;
  size_t msg_prt_thr = msg_count / thr_count;
  std::vector<double> cost_arry(thr_count);
  for (int i = 0; i < thr_count; i++)
  {
    threads.emplace_back([&, i]()
                         {
      //4.线程函数内部开始计时
      auto start = std::chrono::high_resolution_clock::now();
      //5.开始循环写日志
      for(int j = 0;  j < msg_prt_thr; j ++)
      {
        logger->fatal("%s",msg.c_str());
      }
      //6.线程函数内部结束计时
      auto end = std::chrono::high_resolution_clock::now();
      std::chrono::duration<double> cost = end - start;
      cost_arry[i] = cost.count();
      std::cout<<"线程："<<i <<":"<<"\t输出数量："<<msg_prt_thr<<",耗时："<<cost.count()<<"s"<<std::endl; });
  }
  for (int i = 0; i < thr_count; i++)
  {
    threads[i].join();
  }
  // 7.计算总耗时：在多线程中，线程是并发处理的，耗时最高的就是总耗时
  double max_cost = cost_arry[0];
  for (int i = 0; i < thr_count; i++)
  {
    max_cost = max_cost > cost_arry[i] ? max_cost : cost_arry[i];
  }
  size_t msg_per_sec = msg_count / max_cost;                       // 每秒打印多少条
  size_t size_per_sec = (msg_count * msg_len) / (max_cost * 1024); // 每秒打印多少kb
  // 8.进行输出打印
  std::cout << "每秒输出日志数量：" << msg_per_sec << "条\n";
  std::cout << "每秒输出大小：" << size_per_sec << "KB\n";
}
void sync_bench()
{
  std::unique_ptr<xglog::LoggerBuilder> builder(new xglog::globalLoggerBuilder());
  builder->buildLoggername("sync_logger");
  builder->buildFormater("[%c][%f:%l]%m%n");
  builder->buildLoggerType(xglog::LoggerType::LOGGER_SYNC);
  builder->buildSink<xglog::FileSink>("./logfile/test.log");
  builder->build();
  bench("sync_logger", 3, 1000000, 100);
}
// void async_bench()
//  {
//  }
int main()
{
  sync_bench();
  return 0;
}